<?php

/**
 * 插件经理人
 *
 * @author JiangJian <silverd@sohu.com>
 * $Id: Broker.php 156 2012-11-08 01:37:15Z silverd30@gmail.com $
 */

class Core_Plugin_Broker
{
    private static $_plugins = array();

    /**
     * 系统插件注册
     *
     * @return void
     */
    public static function init()
    {
        if ($pluginClasses = Core_Config::load('plugin')) {
            foreach ($pluginClasses as $pluginClass) {
                self::register(new $pluginClass());
            }
        }
    }

    /**
     * 注册新插件
     *
     * @param Core_Plugin_Abstract $plugin
     * @param int $stackIndex
     * @return void
     */
    public static function register(Core_Plugin_Abstract $plugin, $stackIndex = null)
    {
        if (false !== array_search($plugin, self::$_plugins, true)) {
            return;
        }

        $stackIndex = (int) $stackIndex;

        if ($stackIndex) {
            if (isset(self::$_plugins[$stackIndex])) {
                return;
            }
            self::$_plugins[$stackIndex] = $plugin;
        } else {
            $stackIndex = count(self::$_plugins);
            while (isset(self::$_plugins[$stackIndex])) {
                ++$stackIndex;
            }
            self::$_plugins[$stackIndex] = $plugin;
        }

        ksort(self::$_plugins);
    }

    /**
     * 卸载插件
     *
     * @param string|Core_Plugin_Abstract $plugin
     * @return void
     */
    public static function unregister($plugin)
    {
        if ($plugin instanceof Core_Plugin_Abstract) {
            $key = array_search($plugin, self::$_plugins, true);
            if (false === $key) {
                return;
            }
            unset(self::$_plugins[$key]);
        } elseif (is_string($plugin)) {
            foreach (self::$_plugins as $key => $_plugin) {
                if ($plugin == get_class($_plugin)) {
                    unset(self::$_plugins[$key]);
                }
            }
        }
    }

    /**
     * 插件调用
     *
     * @param string $method
     * @return void
     */
    public static function invoke($method)
    {
        if (!self::$_plugins || !$method) {
            return;
        }

        foreach (self::$_plugins as $plugin) {
            if (method_exists($plugin, $method)) {
                $plugin->$method(Core_Request_Http::getInstance(), Core_Response_Http::getInstance());
            }
        }
    }
}